<!-- 创建时间: 2020年12月24日 星期四 15:35 -->
<template>
    <div class="addExaminationQuestions_container">
        <div class="header">
            <el-row>
                <el-col :xs="18" :sm="18" :md="12">
                    <i class="el-icon-back goBack" @click="goBack">返回</i
                    >&nbsp;&nbsp;&nbsp; 添加 {{ classInfo.className }}
                    {{ classInfo.coursesName }} 课程考试试题
                </el-col>
                <el-col :xs="6" :sm="6" :md="12">
                    <el-tag effect="plain" class="totalTopics">
                        <span>单选:{{ totalTopics.get("radio") }}</span>
                        <span>多选:{{ totalTopics.get("checkbox") }}</span>
                        <span>题量:{{ totalTopics.get("totalQuestion") }}</span>
                        <span>总分:{{ totalTopics.get("totalScore") }}</span>
                    </el-tag>
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="查看预览"
                        placement="bottom"
                    >
                        <el-button
                            icon="el-icon-view"
                            circle
                            @click="viewPreview"
                        ></el-button>
                    </el-tooltip>
                    <el-button type="primary" round @click="saveQuestionBank"
                        >保存试题</el-button
                    >
                </el-col>
            </el-row>
        </div>
        <div class="body">
            <div class="aside">
                <el-aside>
                    <el-menu
                        class="el-menu-vertical-demo"
                        @select="handleSelect"
                        :collapse="false"
                    >
                        <el-menu-item index="1">
                            <i class="fa fa-dot-circle-o"></i>
                            <span slot="title">单选题</span>
                        </el-menu-item>
                        <el-menu-item index="2">
                            <i class="fa fa-check-square-o"></i>
                            <span slot="title">多选题</span>
                        </el-menu-item>
                        <el-menu-item index="3">
                            <i class="fa fa-edit"></i>
                            <span slot="title">填空题</span>
                        </el-menu-item>
                    </el-menu>
                </el-aside>
            </div>
            <div class="main">
                <center>
                    <div
                        v-show="questionsList.length == 0"
                        style="color: rgb(191 179 179);font-size: 20px;margin-top: 50px;"
                    >
                        暂无试题信息
                    </div>
                </center>
                <el-card
                    class="box-card"
                    v-for="(item, index) in questionsList"
                    :key="index"
                >
                    <!-- 卡片头部 -->
                    <div slot="header" class="clearfix">
                        <el-row>
                            <!-- 列数 -->
                            <el-col :xs="2" :sm="2" :md="1">
                                <el-button circle>{{ index + 1 }}</el-button>
                            </el-col>
                            <!-- 试题输入框 -->
                            <el-col :xs="22" :sm="18" :md="15">
                                <el-input
                                    type="textarea"
                                    autosize
                                    placeholder="请输入内容"
                                    v-model="item.questionName"
                                >
                                </el-input>
                            </el-col>
                            <!-- 设置分值 -->
                            <el-col
                                :xs="7"
                                :sm="4"
                                :md="4"
                                style="text-align:center;"
                            >
                                <el-tooltip
                                    class="item"
                                    effect="dark"
                                    content="分值"
                                    placement="top"
                                >
                                    <el-input-number
                                        v-model="item.score"
                                        :min="1"
                                        size="mini"
                                    ></el-input-number>
                                </el-tooltip>
                            </el-col>
                            <!-- 试题操作 -->
                            <el-col
                                :xs="4"
                                :sm="3"
                                :md="2"
                                style="text-align:center;"
                            >
                                <el-tooltip
                                    class="item"
                                    effect="dark"
                                    content="上移"
                                    placement="top"
                                >
                                    <i
                                        class="el-icon-caret-top"
                                        @click="moveQuestion('up', index)"
                                    ></i>
                                </el-tooltip>
                                <el-tooltip
                                    class="item"
                                    effect="dark"
                                    content="下移"
                                    placement="top"
                                >
                                    <i
                                        class="el-icon-caret-bottom"
                                        @click="moveQuestion('down', index)"
                                    ></i>
                                </el-tooltip>
                                <el-tooltip
                                    class="item"
                                    effect="dark"
                                    content="删除"
                                    placement="top"
                                >
                                    <i
                                        class="el-icon-delete"
                                        @click="deleteQuestion(index)"
                                    ></i>
                                </el-tooltip>
                            </el-col>
                        </el-row>
                    </div>
                    <!-- 卡片主体 -->
                    <div class="selectList">
                        <div v-for="(ite, idx) in item.optionList" :key="idx">
                            <el-row class="radioList">
                                <el-col :xs="1" :sm="1" :md="1">
                                    <input
                                        :type="item.type"
                                        :name="index"
                                        :value="item.optionList[idx]"
                                        v-model="item.rightOption"
                                    />
                                </el-col>
                                <el-col :xs="20" :sm="15" :md="10">
                                    <el-input
                                        type="textarea"
                                        autosize
                                        placeholder="请输入内容"
                                        v-model="item.optionList[idx]"
                                    ></el-input>
                                </el-col>
                                <el-col :xs="3" :sm="2" :md="2">
                                    <i
                                        class="el-icon-delete"
                                        v-if="
                                            !(item.optionList.length == 1) &&
                                                item.type == 'radio'
                                        "
                                        @click="
                                            item.optionList.splice(idx, 1);
                                            item.rightOption = '';
                                        "
                                    ></i>
                                    <i
                                        class="el-icon-delete"
                                        v-if="
                                            !(item.optionList.length == 1) &&
                                                item.type == 'checkbox'
                                        "
                                        @click="
                                            item.optionList.splice(idx, 1);
                                            item.rightOption.splice(idx, 1);
                                        "
                                    ></i>
                                    <i
                                        class="el-icon-circle-plus-outline"
                                        @click="
                                            item.optionList.splice(
                                                idx + 1,
                                                0,
                                                ''
                                            )
                                        "
                                    ></i>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
        <el-button
            plain
            @click="openInfoTips"
            style="display: none"
        ></el-button>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import $ from "jquery";

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        //这里存放数据
        return {
            classInfo: "", // 班级信息
            questionsList: [], // 试题列表
            totalTopics: new Map([
                ["radio", 0],
                ["checkbox", 0],
                ["totalQuestion", 0],
                ["totalScore", 0],
            ]),
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {
        questionsList: {
            handler(newVal, oldVal) {
                this.totalTopics = new Map([
                    ["radio", 0],
                    ["checkbox", 0],
                    ["totalQuestion", 0],
                    ["totalScore", 0],
                ]);
                newVal.forEach((value, index) => {
                    value.id = index + 1;
                    this.calcTotalTopics(value);
                });
                this.totalTopics.set(
                    "totalQuestion",
                    this.questionsList.length
                );
            },
            deep: true, //深度监听
        },
    },
    //方法集合
    methods: {
        // 返回
        goBack() {
            this.$router.push({
                path: this.$route.query.form,
            });
        },
        calcTotalTopics(newVal) {
            if (
                this.questionsList.length >
                this.totalTopics.get("totalQuestion")
            ) {
                this.totalTopics.set(
                    newVal.type,
                    this.totalTopics.get(newVal.type) + 1
                );
            } else if (
                this.questionsList.length <
                this.totalTopics.get("totalQuestion")
            ) {
                this.totalTopics.set(
                    newVal.type,
                    this.totalTopics.get(newVal.type) - 1
                );
            }
            this.totalTopics.set(
                "totalScore",
                this.totalTopics.get("totalScore") + newVal.score
            );
        },
        // 添加试题类型
        handleSelect(key, keyPath) {
            switch (key) {
                case "1":
                    let obj = this.randomQuestions();
                    this.questionsList.push({
                        id: -1,
                        questionName: obj.questionName, // 单选是目
                        type: "radio", // 类型
                        rightOption: obj.rightOption, // 正确选项
                        score: 2, // 分值
                        optionList: obj.randomOptionList, // 选项列表
                    });
                    break;
                case "2":
                    this.questionsList.push({
                        id: -1,
                        questionName: "下面说法正确的是()",
                        type: "checkbox",
                        score: 3, // 分值
                        optionList: [
                            "如果某公共接口被声明在一个源文件中，则接口必须与源文件具有相同名字。",
                            "如果源文件包含import语句，则该语句必须是除空行和注释行外的第一个语句行。",
                            "如果某源文件包含package语句，则该语句必须是第一个非空、非注释行。",
                            "接口中的方法必定是抽象方法，但可以不用关键字abstract修饰。",
                        ], // 选项列表
                        rightOption: [], // 正确答案
                    });
                    break;
                case "3":
                    // console.log("填空题");
                    break;
                default:
                    break;
            }
        },

        // 删除试题
        deleteQuestion(index) {
            this.questionsList.splice(index, 1);
        },
        // 移动试题
        moveQuestion(option, index) {
            if (option == "up") {
                if (index != 0) {
                    let temp = this.questionsList[index - 1];
                    this.questionsList[index - 1] = this.questionsList[index];
                    this.questionsList[index] = temp;
                    this.$forceUpdate();
                } else {
                    this.$message("这已经是第一条了");
                }
            } else if (option == "down") {
                if (index != this.questionsList.length - 1) {
                    let temp = this.questionsList[index + 1];
                    this.questionsList[index + 1] = this.questionsList[index];
                    this.questionsList[index] = temp;
                    this.$forceUpdate();
                } else {
                    this.$message("这已经是最后一条了");
                }
            }
        },
        // 修改试题标题
        modifyQuestionTiele() {
            let el = document.getElementsByClassName("editDiv");
            let _this = this;
            for (let i = 0; i < el.length; i++) {
                el[i].addEventListener("focusout", function(e) {
                    _this.questionsList[
                        e.srcElement.id
                    ].questionName = e.srcElement.innerText
                        .replace(/[\s\r\n]/g, "")
                        .trim();
                });
            }
        },
        // 查看预览
        viewPreview() {
            if (this.questionsList.length != 0) {
                this.$store.commit("setQuestionsList", this.questionsList);
                let openViewPage = this.$router.resolve({
                    path: "/viewPreview",
                    
                });
                window.open(openViewPage.href, "_blank");
            } else {
                this.$message("暂无试题信息");
            }
        },
        // 保存试题
        saveQuestionBank() {
            // 本地保存一份 便于再次编辑
            this.$store.commit("setQuestionsList", this.questionsList);
            // 若用户清空所有试题 且 有试题库的情况下 --需要单独处理
            if (
                this.questionsList.length == 0 &&
                this.classInfo.questionBank != "null"
            ) {
                this.$http
                    .post("clearAllQuestionBank", {
                        questionBankName: this.classInfo.questionBank,
                    })
                    .then((res) => {
                        if (res.body) {
                            this.openInfoTips(
                                "提示",
                                "试题库已清空",
                                "success",
                                3000
                            );
                        } else {
                            this.openInfoTips(
                                "提示",
                                "系统错误,请稍后重试",
                                "error",
                                3000
                            );
                        }
                    });
                return;
            }

            // 保存数据库，持久化信息存储
            let data = JSON.parse(JSON.stringify(this.questionsList));
            for (let i = 0; i < data.length; i++) {
                data[i].optionList = data[i].optionList.join("&");
                if (data[i].type == "checkbox") {
                    data[i].rightOption = data[i].rightOption.join("&");
                }
            }
            this.$http
                .post("saveQuestionBank", {
                    id: this.classInfo.id,
                    questionsList: JSON.stringify(data),
                })
                .then((res) => {
                    if (res.body == true) {
                        this.openInfoTips(
                            "成功",
                            "试题添加成功",
                            "success",
                            3000
                        );
                    } else {
                        this.openInfoTips("提示", res.body, "info", 3000);
                    }
                });
        },
        // 进入添加试题前，自动获取已添加的试题信息
        autoGetQuestionBankInfo() {
            if (this.classInfo.questionBank == undefined) {
                return;
            }
            this.$http
                .post("autoGetQuestionBankInfo", {
                    questionBankName: this.classInfo.questionBank,
                })
                .then((res) => {
                    if (res.body != null) {
                        let str = JSON.parse(res.bodyText);
                        for (let i = 0; i < str.length; i++) {
                            str[i].optionList = str[i].optionList.split("&");
                            if (str[i].type != "radio") {
                                str[i].rightOption = str[i].rightOption.split(
                                    "&"
                                );
                            }
                        }
                        this.questionsList = str;
                    }
                });
        },
        openInfoTips(title, message, type, duration) {
            this.$notify({
                title: title,
                message: message,
                type: type,
                duration: duration,
                dangerouslyUseHTMLString: true,
            });
        },
        // 元素节点交换 -- 目前暂没有用上
        elementSwap(aNode, bNode) {
            let aParent = aNode.parentNode;
            let bParent = bNode.parentNode;
            if (aParent && bParent) {
                let cloneNode = aNode.cloneNode(true);
                cloneNode.radio = aNode.radio;
                cloneNode.radioCount = aNode.radioCount;
                bParent.replaceChild(cloneNode, bNode);
                aParent.replaceChild(bNode, aNode);
            }
        },
        // 随机试题生产----开发阶段使用
        randomQuestions() {
            // 生产数学试题
            // 返回题干、选项、正确答案
            let l = 1,
                r = 10;
            let symbolList = ["+", "-", "*", "/"];
            let number1 = Math.round(Math.random() * r + l); //[1-10]
            let number2 = Math.round(Math.random() * r + l);
            let indexSymbol = parseInt(Math.random() * symbolList.length);
            let symbol = symbolList[indexSymbol];
            let questionName = number1 + "" + symbol + "" + number2 + "=( )";
            let rightOption = 0;
            switch (indexSymbol) {
                case 0:
                    rightOption = number1 + number2;
                    break;
                case 1:
                    rightOption = number1 - number2;
                    break;
                case 2:
                    rightOption = number1 * number2;
                    break;
                case 3:
                    rightOption = number1 / number2;
                    break;
            }
            let randomOptionList = [];
            let randomRifhtOptionIndex = parseInt(Math.random() * 4);
            for (let j = 0; j < 4; j++) {
                if (j != randomRifhtOptionIndex) {
                    randomOptionList[j] = Math.round(Math.random() * 100 + 1);
                } else {
                    randomOptionList[j] = rightOption;
                }
            }
            return {
                questionName: questionName,
                rightOption: rightOption,
                randomOptionList: randomOptionList,
            };
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.classInfo = this.$store.getters.getAddQuestions;
        this.autoGetQuestionBankInfo();
        if (
            this.$store.getters.getQuestionsList.length !=
            this.questionsList.length
        ) {
            this.$store.commit("setQuestionsList", []);
        }
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    //当data中定义的数据有变化时就会加载updated方法
    updated() {},
};
</script>

<style lang="scss">
//@import url(); 引入公共css类
.addExaminationQuestions_container {
    padding-bottom: 15px;
    .header {
        line-height: 60px;
        width: 100%;
        background-color: #b3c0d1;
        position: fixed;
        left: 0;
        top: 0;
        z-index: 2;
        .goBack {
            cursor: pointer;
        }
        .el-row {
            padding: 0 10px;
        }
        .el-row div:nth-child(2) {
            text-align: right;
        }
        .el-row div:nth-child(1) {
            overflow: hidden;
        }
        .totalTopics {
            font-size: 16px;
            margin-right: 15px;
            span {
                margin-right: 15px;
            }
        }
    }
    .body {
        display: flex;
        margin-top: 65px;
        .aside {
            height: auto;
            position: fixed;
            user-select: none;
            .el-aside {
                width: 160px !important;
                .el-menu-vertical-demo:not(.el-menu--collapse) {
                    min-height: 400px;
                    text-align: center;
                    background: #d3dce6;
                    width: 160px;
                    border: none;
                }
            }
        }
        .main {
            // height: 600px;
            width: 100%;
            margin-left: 165px;
            .el-card.box-card {
                margin-bottom: 13px;
                .clearfix {
                    .el-row {
                        line-height: 40px;
                        i {
                            display: inline;
                        }
                        .editDiv:hover {
                            background: #efe8c9;
                        }
                    }
                }
                .selectList {
                    .radioList,
                    .checkList {
                        line-height: 35px;
                        div:first-child {
                            text-align: center;
                        }
                        div:last-child {
                            text-align: center;
                            cursor: pointer;
                        }
                    }
                }
            }
            .el-card.box-card.is-always-shadow > div:nth-child(1) {
                padding: 12px 20px;
            }
            .box-card:hover {
                margin-bottom: 13px;
                .clearfix {
                    .el-row {
                        i {
                            display: inline;
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }
}
</style>
